package com.xunji.standard.util;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Component
public class RestTemplateUtils {
    /**
     * 反射修改header信息
     *
     * @param request
     * @param key
     * @param value
     */
    private static final String SPECIAL_CLASS = "org.springframework.web.multipart.support.StandardMultipartHttpServletRequest";


    public static <T> T uploadFile(String url, MultiValueMap<String, Object> form, Class<T> clazz) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        return restTemplate.postForObject(url, files, clazz);
    }

    public static <T> T get(String url, Class<T> clazz) {
        return new RestTemplate().getForObject(url, clazz);
    }

    public static <T> T post(String url, Map<String, Object> param, Class<T> clazz) {
        return new RestTemplate().postForObject(url, param, clazz);
    }

    public static <T> T delete(String url, Map<String, Object> param, Class<T> clazz) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json");
        headers.setContentType(type);
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(param), headers);
        ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.DELETE, entity, clazz);
        return exchange.getBody();
    }


    public static void downLoadFile(String absFile, HttpServletResponse response) {
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            File file = new File(absFile);
            String fileName = file.getName();
            log.info("下载文件->{}", fileName);
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buff = new byte[bis.available()];
            bis.read(buff);
            bis.close();
            response.reset();
            response.setCharacterEncoding("UTF-8"); //设置编码字符
            response.setContentType("application/octet-stream"); //设置下载内容类型
//            response.setContentType("application/zip"); //设置下载内容类型
            response.addHeader("Content-Length", "" + file.length());
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
            os = new BufferedOutputStream(response.getOutputStream());
            os.write(buff);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            log.error("文件下载失败！ file={}", absFile, e);
        } catch (IOException e) {
            log.error("文件下载失败！ file={}", absFile, e);
        } finally {
            if (null != bis) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * http文件导出
     *
     * @param inputStream 输入流
     * @param fileName    文件名
     * @param response    response
     */
    public static void downLoadFile(InputStream inputStream, String fileName, HttpServletResponse response) {
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            log.info("下载文件->{}", fileName);
            //bis = new BufferedInputStream(inputStream);
            //byte[] buff = new byte[bis.available()];
            //bis.read(buff);
            //bis.close();
            response.reset();
            response.setContentType("application/octet-stream"); //设置下载内容类型
            response.setCharacterEncoding("UTF-8"); //设置编码字符
            //response.setContentType("application/zip"); //设置下载内容类型
            //response.addHeader("Content-Length", "" + inputStream.available());
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            //response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
            os = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            byte[] data = new byte[1024];
            while ((len = inputStream.read(data)) != -1) {
                os.write(data, 0, len);
            }
            os.write(data);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error("文件下载失败！ file={}", fileName, e);
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
